#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# zhouyi 6098550@qq.com


# READ_COILS               读线圈
# READ_DISCRETE_INPUTS     读离散输入
# READ_HOLDING_REGISTERS   读保持寄存器
# READ_INPUT_REGISTERS     读输入寄存器
# WRITE_SINGLE_COIL        写单一线圈
# WRITE_SINGLE_REGISTER    写单一寄存器
# WRITE_MULTIPLE_COILS     写多个线圈
# WRITE_MULTIPLE_REGISTERS 写多个寄存器
#
# from pymodbus.client.sync import ModbusSerialClient as ModbusClient
# client = ModbusClient(
#     method   = 'rtu',
#     port     = 'COM5',
#     stopbits = 1,
#     bytesize = 8,
#     parity   = 'E',
#     baudrate = 19200,
#     timeout  = 1)
# client.connect()
#
# rr = client.read_holding_registers(100, 10, unit=1)
# print rr.registers
#
# while 1:
# 	rr = client.read_holding_registers(110, 1, unit=1)
# 	print rr.registers
#
# client.close()

BASE_WEIGHT     =100
V1_WEIGHT       =101
V2_WEIGHT       =102
V3_WEIGHT       =103

START_WORK      =104
STOP_WORK       =105
ABORT_WORK      =106
WORK_STATUS     =110

#from mi_config            import MiConfig as MiConfig
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
class MiMachineClient:

    def __init__(self, config):
        self.client = ModbusClient(
            method   = config.method,
            port     = config.port,
            stopbits = config.stopbits,
            bytesize = config.bytesize,
            parity   = config.parity,
            baudrate = config.baudrate,
            timeout  = config.timeout)
        self.client.connect()

    #def __del__(self):
        self.Close()

    def Write(self, address, value):
        rq = self.client.write_register(address, value, unit=1)
        rr = self.client.read_holding_registers(address, 1, unit=1)
        self.ReadAll()
        return rr.registers[0]

    def Read(self, address):
        rr = self.client.read_holding_registers(address, 1, unit=1)
        return rr.registers[0]

    def ReadAll(self):
        rr = self.client.read_holding_registers(100, 10, unit=1)
        print rr.registers

    def Listen(self):
        while 1:
            rr = self.client.read_holding_registers(110, 1, unit=1)
            print rr.registers[0]

    def Close(self):
        self.client.close()


########################################################################################################################
## for test
#config = MiConfig()
#config.Load('./config.json')
#config.Show()


#machine_client = MiMachineClient(config.machine_config)
#machine_client.ReadAll()
#machine_client.Write(102, 1)
# print machine_client.Read()
# machine_client.Write(102, 2)
# print machine_client.Read()
# machine_client.Write(102, 3)
# print machine_client.Read()
# machine_client.Write(102, 20)
# print machine_client.Read()
# machine_client.Write(102, 30)
# print machine_client.Read()
# machine_client.Listen()
# machine_client.Close()



